package com.jack.thinking.java._22.swing.concurrent;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Callable;

import javax.swing.JButton;
import javax.swing.JFrame;

import com.jack.thinking.java._22.swing.concurrent.entity.TaskItem;
import com.utils.SwingConsole;
import com.utils.TaskManager;

public class InterruptedLongRunningCallable extends JFrame{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JButton b1 = new JButton("Start Long Running Task");
	private JButton b2 = new JButton("End Long Running Task");
	private JButton b3 = new JButton("Get results");
	
	private TaskManager<String, CallableTask> manager = new TaskManager<String, CallableTask>();
	public InterruptedLongRunningCallable() {
		b1.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				CallableTask task = new CallableTask();
				manager.add(task);
				System.out.println(task + " add to the queue");
			}
		});
		
		b2.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				for(String result : manager.purge()) {
					System.out.println(result);
				}
			}
		});
		
		b3.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				for(TaskItem<String, CallableTask> tt : manager) {
					tt.task.id();
				}
				
				for(String r : manager.getResults()) {
					System.out.println(r);
				}
			}
		});
		
		setLayout(new FlowLayout());
		add(b1);
		add(b2);
		add(b3);
	}
	
	public static void main(String[] args) {
		SwingConsole.run(new InterruptedLongRunningCallable(), 200, 150);
	}
}

class CallableTask extends Task implements Callable<String>{

	@Override
	public String call() throws Exception {
		run();
		return "Return value of " + this;
	}
	
}